//
//  RxWebViewController.m
//  RxWebViewController
//
//  Created by roxasora on 15/10/23.
//  Copyright © 2015年 roxasora. All rights reserved.
//

#import "RxWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "NSURLRequest+Cateory.h"
#import <objc/runtime.h>
#define boundsWidth self.view.bounds.size.width
#define boundsHeight self.view.bounds.size.height

@protocol YPJSExport <JSExport>

/**
 获取用户token
 */
- (void)jsGetAppToken;

/**
 切换到投资列表页面
 */
- (void)jsShowAppBorrowList;
//* JSExportAs的作用是用jsShowAppLoginWithParameter:的OC方法来作为JS方法jsShowAppLoginPage的别名(oc方法来定义js方法)
JSExportAs(jsShowAppLoginPage, - (void)jsShowAppLoginWithParameter:(NSString *)parameter);


/**
 跳转到"我的"页面
 */
- (void)jsShowMyAccount;

@end

//必须将YPJSExport导入到该控制器，否则跟JS关联不上。
@interface RxWebViewController ()<UIWebViewDelegate,UINavigationControllerDelegate,UINavigationBarDelegate,UIGestureRecognizerDelegate,YPJSExport>

@property (nonatomic)JSContext *context;
@property (nonatomic)UIBarButtonItem* customBackBarItem;
@property (nonatomic)UIBarButtonItem* closeButtonItem;


/**
 *  array that hold snapshots
 */
@property (nonatomic)NSMutableArray* snapShotsArray;

/**
 *  current snapshotview displaying on screen when start swiping
 */
@property (nonatomic)UIView* currentSnapShotView;

/**
 *  previous view
 */
@property (nonatomic)UIView* prevSnapShotView;

/**
 *  background alpha black view
 */
@property (nonatomic)UIView* swipingBackgoundView;

/**
 *  left pan ges
 */
@property (nonatomic)UIPanGestureRecognizer* swipePanGesture;

/**
 *  if is swiping now
 */
@property (nonatomic)BOOL isSwipingBack;

@end

@implementation RxWebViewController

-(UIStatusBarStyle) preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - init
-(instancetype)initWithUrl:(NSString *)url{
    self = [super init];
    if (self) {
        self.url = [NSURL URLWithString:url];
        _progressViewColor = [UIColor colorWithRed:119.0/255 green:228.0/255 blue:115.0/255 alpha:1];
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.webView];
    
    self.navigationController.navigationItem.hidesBackButton=YES;
    
    NSURLRequest *request=[NSURLRequest requestWithURL: self.url];
    
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[request.URL host]];
        
    self.webView.scalesPageToFit=YES;
    
    self.webView.delegate=self;
    
    
    [self.webView loadRequest:request];
    

}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    self.webView.delegate = nil;
}


#pragma mark - public funcs
-(void)reloadWebView{
    [self.webView reload];
}

#pragma mark - logic of push and pop snap shot views
-(void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request{
    //    NSLog(@"push with request %@",request);
    NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"];
    
    //如果url是很奇怪的就不push
    if ([request.URL.absoluteString isEqualToString:@"about:blank"]) {
        //        NSLog(@"about blank!! return");
        return;
    }
    //如果url一样就不进行push
    if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) {
        return;
    }
    
    UIView* currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];
    [self.snapShotsArray addObject:
     @{
       @"request":request,
       @"snapShotView":currentSnapShotView
       }
     ];
    NSLog(@"now array count %lu \ncurrentUrl==%@",(unsigned long)self.snapShotsArray.count,request.URL.absoluteString);
}

-(void)startPopSnapshotView{
    if (self.isSwipingBack) {
        return;
    }
    if (!self.webView.canGoBack) {
        
        if (self.navigationController.viewControllers.count>3) {
            
            if (_isCurrentVC) {
                
                
                
                [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-3] animated:YES];
                
                
            }else{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            
        }
        
        //        [self.navigationController popViewControllerAnimated:YES];
        
        return;
    }
    self.isSwipingBack = YES;
    //create a center of scrren
    CGPoint center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
    
    self.currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];
    
    //add shadows just like UINavigationController
    self.currentSnapShotView.layer.shadowColor = [UIColor whiteColor].CGColor;
    self.currentSnapShotView.layer.shadowOffset = CGSizeMake(3, 3);
    self.currentSnapShotView.layer.shadowRadius = 5;
    self.currentSnapShotView.layer.shadowOpacity = 0.75;
    
    //move to center of screen
    self.currentSnapShotView.center = center;
    
    self.prevSnapShotView = (UIView*)[[self.snapShotsArray lastObject] objectForKey:@"snapShotView"];
    center.x -= 60;
    self.prevSnapShotView.center = center;
    self.prevSnapShotView.alpha = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.prevSnapShotView];
    [self.view addSubview:self.swipingBackgoundView];
    [self.view addSubview:self.currentSnapShotView];
}

-(void)popSnapShotViewWithPanGestureDistance:(CGFloat)distance{
    if (!self.isSwipingBack) {
        return;
    }
    
    if (distance <= 0) {
        return;
    }
    
    CGPoint currentSnapshotViewCenter = CGPointMake(boundsWidth/2, boundsHeight/2);
    currentSnapshotViewCenter.x += distance;
    CGPoint prevSnapshotViewCenter = CGPointMake(boundsWidth/2, boundsHeight/2);
    prevSnapshotViewCenter.x -= (boundsWidth - distance)*60/boundsWidth;
    //    NSLog(@"prev center x%f",prevSnapshotViewCenter.x);
    
    self.currentSnapShotView.center = currentSnapshotViewCenter;
    self.prevSnapShotView.center = prevSnapshotViewCenter;
    self.swipingBackgoundView.alpha = (boundsWidth - distance)/boundsWidth;
}

-(void)endPopSnapShotView{
    if (!self.isSwipingBack) {
        return;
    }
    
    //prevent the user touch for now
    self.view.userInteractionEnabled = NO;
    
    if (self.currentSnapShotView.center.x >= boundsWidth) {
        // pop success
        [UIView animateWithDuration:0.2 animations:^{
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            
            self.currentSnapShotView.center = CGPointMake(boundsWidth*3/2, boundsHeight/2);
            self.prevSnapShotView.center = CGPointMake(boundsWidth/2, boundsHeight/2);
            self.swipingBackgoundView.alpha = 0;
        }completion:^(BOOL finished) {
            [self.prevSnapShotView removeFromSuperview];
            [self.swipingBackgoundView removeFromSuperview];
            [self.currentSnapShotView removeFromSuperview];
            [self.webView goBack];
            [self.snapShotsArray removeLastObject];
            self.view.userInteractionEnabled = YES;
            
            self.isSwipingBack = NO;
        }];
    }else{
        //pop fail
        [UIView animateWithDuration:0.2 animations:^{
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            
            self.currentSnapShotView.center = CGPointMake(boundsWidth/2, boundsHeight/2);
            self.prevSnapShotView.center = CGPointMake(boundsWidth/2-60, boundsHeight/2);
            self.prevSnapShotView.alpha = 1;
        }completion:^(BOOL finished) {
            [self.prevSnapShotView removeFromSuperview];
            [self.swipingBackgoundView removeFromSuperview];
            [self.currentSnapShotView removeFromSuperview];
            self.view.userInteractionEnabled = YES;
            
            self.isSwipingBack = NO;
        }];
    }
}

#pragma mark - update nav items

-(void)updateNavigationItems{
    if (self.webView.canGoBack) {
        UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        spaceButtonItem.width = -6.5;
        
        [self.navigationItem setLeftBarButtonItems:@[self.customBackBarItem,self.closeButtonItem] animated:NO];

    }else{
        
        [self.navigationItem setLeftBarButtonItems:@[self.customBackBarItem]];
    }
}

#pragma mark - events handler
-(void)swipePanGestureHandler:(UIPanGestureRecognizer*)panGesture{
    CGPoint translation = [panGesture translationInView:self.webView];
    CGPoint location = [panGesture locationInView:self.webView];
    //    NSLog(@"pan x %f,pan y %f",translation.x,translation.y);
    
    if (panGesture.state == UIGestureRecognizerStateBegan) {
        if (location.x <= 50 && translation.x > 0) {  //开始动画
            [self startPopSnapshotView];
        }
    }else if (panGesture.state == UIGestureRecognizerStateCancelled || panGesture.state == UIGestureRecognizerStateEnded){
        [self endPopSnapShotView];
    }else if (panGesture.state == UIGestureRecognizerStateChanged){
        [self popSnapShotViewWithPanGestureDistance:translation.x];
    }
}

-(void)customBackItemClicked{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        
        if (_isCurrentVC) {
            
            
            [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-3] animated:YES];
            
            
        }else{
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        
    }
    
}

-(void)closeItemClicked{
    
    
    if (_isCurrentVC) {
        
        
        [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-3] animated:YES];
        
        
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
    //    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- JS-OC交互
/**
 JS获取token
 */
- (void)jsGetAppToken{
    
    if (TOKEN) {
        
        [YPHttpRequestMethod sendAsyRequestURL:YPVerifyToken_URL withData:@{@"token":TOKEN} withCompletionBlock:^(NSDictionary *responseDictionary) {
            
            if ([responseDictionary[@"status"] integerValue] == 0) {
                NSString *jsStr = [NSString stringWithFormat:@"appTokenCallback('%@')",TOKEN];
                [_context evaluateScript:jsStr];
            }else{
                [self jsShowAppLoginWithParameter:nil];
            }
        } withFailedBlock:^(NSError *error) {
            
        } withIndicator:NO atView:nil];
        
    }else{
        
        [self jsShowAppLoginWithParameter:nil];
    }

}

/**
 切换到投资列表页面
 */
- (void)jsShowAppBorrowList{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //先返回值根试图控制器
        [self.navigationController popToRootViewControllerAnimated:NO];
        if(APPDelegate.mainTabbar.selectedIndex != 1){
            
            APPDelegate.mainTabbar.selectedIndex = 1;
            UINavigationController *nav = APPDelegate.mainTabbar.viewControllers[1];
            if (nav.viewControllers.count > 1) {
                [nav popToRootViewControllerAnimated:YES];
            }
        }
        
    });
    
}

/**
 唤起登录界面
 
 @param parameter nil
 */
- (void)jsShowAppLoginWithParameter:(NSString *)parameter{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self goToLoginVCWithCompleteBlock:^(NSString *token){
            
            NSString *jsStr = [NSString stringWithFormat:@"appTokenCallback('%@')",TOKEN];
            [_context evaluateScript:jsStr];
        }];
    });
    
}

/**
 跳转到"我的"页面
 */
- (void)jsShowMyAccount{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        BOOL shouldGo = YES;
        UINavigationController *currentNav = (UINavigationController *)APPDelegate.mainTabbar.selectedViewController;
        //过滤掉以下控制器触发的JS方法（投标页面、债权转让认购页面、自动投标列表(这个方法showHsBoxWithFlag:)）
        for (UIViewController *vc in currentNav.viewControllers) {
            if ([vc isKindOfClass:[NSClassFromString(@"YPTenderViewController") class]] ||
                [vc isKindOfClass:[NSClassFromString(@"YPZQSureViewController") class]] ||
                [vc isKindOfClass:[NSClassFromString(@"YPAutoTenderViewController") class]]) {
                
                shouldGo = NO;
                break;
            }
        }
        if (shouldGo) { //跳转到我的
            //先返回值根试图控制器
            [currentNav popToRootViewControllerAnimated:NO];
            
            if(APPDelegate.mainTabbar.selectedIndex != 3)APPDelegate.mainTabbar.selectedIndex = 3;
            
            UINavigationController *nav = APPDelegate.mainTabbar.viewControllers[3];
            [nav popToRootViewControllerAnimated:YES];
        }else{ //pop回去
            
            [currentNav popViewControllerAnimated:YES];
        }
    });
}

#pragma mark - webView delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [MBProgressHUD showHUDAddedTo:webView animated:YES];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //    NSLog(@"navigation type %d",navigationType);
    switch (navigationType) {
        case UIWebViewNavigationTypeLinkClicked: {
            [self pushCurrentSnapshotViewWithRequest:request];
            break;
        }
        case UIWebViewNavigationTypeFormSubmitted: {
            [self pushCurrentSnapshotViewWithRequest:request];
            break;
        }
        case UIWebViewNavigationTypeBackForward: {
            break;
        }
        case UIWebViewNavigationTypeReload: {
            break;
        }
        case UIWebViewNavigationTypeFormResubmitted: {
            break;
        }
        case UIWebViewNavigationTypeOther: {
            [self pushCurrentSnapshotViewWithRequest:request];
            break;
        }
        default: {
            break;
        }
    }
    [self updateNavigationItems];
    
    if ([request.URL.absoluteString rangeOfString:@"jsGetAppToken"].location != NSNotFound) {
        
        [self jsGetAppToken];
    }
    
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [MBProgressHUD hideHUDForView:webView animated:YES];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (theTitle.length > 10) {
        theTitle = [[theTitle substringToIndex:9] stringByAppendingString:@"…"];
    }
    self.title = theTitle;
    //    [self.progressView setProgress:1 animated:NO];
    
    _context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    _context[@"appObj"] = self;
    NSString *jsStr = [NSString stringWithFormat:@"if(typeof pageLoadFinished=='function'){pageLoadFinished();}"];
    [_context evaluateScript:jsStr];
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [MBProgressHUD hideHUDForView:webView animated:YES];
}

#pragma mark - NJProgress delegate



#pragma mark - setters and getters
-(void)setUrl:(NSURL *)url{
    _url = url;
}

-(UIWebView*)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        _webView.delegate = (id)self;
        _webView.scalesPageToFit = YES;
        _webView.backgroundColor = [UIColor whiteColor];
        [_webView addGestureRecognizer:self.swipePanGesture];
    }
    return _webView;
}

-(UIBarButtonItem*)customBackBarItem{
    if (!_customBackBarItem) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        
        
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_008"] forState:UIControlStateNormal];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_008"] forState:UIControlStateHighlighted];
        
        btn.size = btn.currentBackgroundImage.size;
        [btn addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _customBackBarItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _customBackBarItem;
}

-(UIBarButtonItem*)closeButtonItem{
    if (!_closeButtonItem) {
        
        
        UIButton* backButton = [[UIButton alloc] init];
        
        backButton.frame=CGRectMake(0, 0, 50, 50);
        
        
        [backButton setTitle:@"关闭" forState:0];
        
        [backButton addTarget:self action:@selector(closeItemClicked) forControlEvents:UIControlEventTouchUpInside];
        
        _closeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        
    }
    return _closeButtonItem;
}

-(UIView*)swipingBackgoundView{
    if (!_swipingBackgoundView) {
        _swipingBackgoundView = [[UIView alloc] initWithFrame:self.view.bounds];
        _swipingBackgoundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    }
    return _swipingBackgoundView;
}

-(NSMutableArray*)snapShotsArray{
    if (!_snapShotsArray) {
        _snapShotsArray = [NSMutableArray array];
    }
    return _snapShotsArray;
}

-(BOOL)isSwipingBack{
    if (!_isSwipingBack) {
        _isSwipingBack = NO;
    }
    return _isSwipingBack;
}

-(UIPanGestureRecognizer*)swipePanGesture{
    if (!_swipePanGesture) {
        _swipePanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(swipePanGestureHandler:)];
        _swipePanGesture.delegate = self;
    }
    return _swipePanGesture;
}

#pragma mark -- UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    
    return self.webView.canGoBack;
}

@end

#pragma mark - implement the navigationController in category

@interface UINavigationController (RxWebView)<UINavigationBarDelegate>

@end

@implementation UINavigationController (RxWebView)

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

//!make sure I managed the back item pop event
//!这一步是截获系统 返回键 的事件，来自己处理
-(BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item{
    if ([self.viewControllers.lastObject class] == [RxWebViewController class]) {
        RxWebViewController* webVC = (RxWebViewController*)self.viewControllers.lastObject;
        if (webVC.webView.canGoBack) {
            [webVC.webView goBack];
            
            
            
            //!make sure the back indicator view alpha back to 1
            [[self.navigationBar subviews] lastObject].alpha = 1;
            return NO;
        }else{
            [self popViewControllerAnimated:YES];
            return YES;
        }
    }
    return YES;
}


@end
